/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, {Component} from 'react';
import {
	Alert,
	DeviceEventEmitter,
	Dimensions,
	Modal,
	StyleSheet,
	Text,
	TextInput,
	TouchableOpacity,
	View,
} from 'react-native';
// 在你需要用到的页面，导入
import DateUtil from './component/DateUtil';
import DigitUtil from './component/DigitUtil';
import Toast from '@remobile/react-native-toast';
import BluetoothSerial from 'react-native-bluetooth-serial';
import getStyles from '../style/styles';

const {ESC} = BluetoothSerial;
import axiosInstance from './utils/request';

//屏幕信息
var dimensions = require('Dimensions');
//获取屏幕的宽度
const WIN_WIDTH = Dimensions.get('window').width;
var width = WIN_WIDTH/2;

let styles={};
export default class PayScene extends Component {

	constructor(props){
		super(props);
		const {params} = this.props.route;
		this.props.navigation.setOptions({
			title:'用户缴费'
		})
		//this.jump = this.jump.bind(this);
		this.state={
			custCode:params.custCode,
			currMonth:params.currMonth,
			name:global.user.userData.name,
			bookName:"",
			custName:"",
			tel:"",
			address: "",
			payfee:"",
			natureName:"",
			balance: 0.00,
			arrears: 0.00,
			surplus:0.00,
			months:0,
			priorReading:0.00,
			currReading:0.00,
			quantity:0.00,
			sumQuantity:0.00,
			waterCost:0.00,
			sewageCost:0.00,
			healthCost:0.00,
			lateFee:0.00,
			totalFact:0.00,
			sumFact:0.00,

			isEnabled: false,
			devices: [],
			discovering: false,
			animationType: 'none',//none slide fade
			modalVisible: false,//模态场景是否可见
			transparent: false,//是否透明显示
			counter:0,//已连接设备数

			isOpenBlueM: false, // 是否打开蓝牙
			doesConnected: false, // 是否连接
			isConnecting: false, // 是否正常连接,用于点击已配对设备
			isPairingBlueMDevice: false, // 是否正在配对设备
			connectTipsText: '正在连接',
			currentConnectDevice: {}, // 当前点击连接的设备
			pairDeviceData: [], // 已经配对的设备
			unPairDeviceArray: [], // 未配对的设备
			isShowActivityIndicator: false, // 是否显示加载提示
		};
	}

	setModalVisible = (visible) => {
    	this.setState({ modalVisible: visible });
    }

	componentDidMount() {
        // 判断蓝牙是否可用
        BluetoothSerial.isEnabled().then(result => {
			this.setState({
				isEnabled: result
			});
        }).catch((err)=>{
			Alert.alert(error);
		})

		let number=0;
		this.toggleBluetooth(true);
		this.discoverUnpaired();
		BluetoothSerial.list().then(devices => {
			if(devices.length==0){
				Alert.alert('提示','蓝牙未配对，请在蓝牙设置中进行配对！');
				return;
			}

			//遍历已配对设备，
			devices.map((device, i) => {
				if (this.state.isConnecting) return
				BluetoothSerial.isConnected()
				.then((results) => {
					if(results){
						number++;
						this.setState({
							counter:number
						});
						Toast.showShortCenter('蓝牙已连接！');
					}
				})
				.catch((err) => {
					console.log('isConnected：'+err);
				})
			});

			if(number==0){
				Alert.alert('提示', '蓝牙未连接，确定要连接吗？',
					[
						{
							text: '确定',
							onPress: ()=> this.gotoPage('BluetoothScene')
						},
						{
							text: '取消',
							onPress: () => console.log('点击取消')
						}
					]
				)
			}
        }).catch((err) => {
			console.log('BluetoothSerial.list()：'+err);
		})

		//收到监听
		this.listener = DeviceEventEmitter.addListener('print', (params) => {
			//收到监听后想做的事情
			if(params.payMode=='2'){
				this.printBill();
			}
		})
		const data = {
			custCode:this.state.custCode,
			payfee:0
	  	};
		this.fetchData(data).then((res) => {
			this.setData(res);
		}).catch((error)=>{
			Alert.alert(error);
		})
    }

	componentWillUnmount() {
		this.listener.remove();
	};

	gotoPage(scene){
		this.props.navigation.navigate(scene);
	}

	fetchData(data){
		return new Promise((resolve, reject) =>{
			let url=global.server.url+'/custPrepay/selectArrears';
			axiosInstance({
				method: 'post',
				url: url,
				data: data
			}).then(res => {
				resolve(res);
			}).catch(err => {
				reject(err);
				console.log('网络异常，请稍后再试！'+err);
			})
		});
	}

	fetchPayment(data){
		return new Promise((resolve, reject) =>{
			let url=global.server.url+'/costHis/selectCostHis';
			axiosInstance({
				method: 'post',
				url: url,
				data: data
			}).then(res => {
				resolve(res);
			}).catch(err => {
				reject(err);
				console.log('网络异常，请稍后再试！'+err);
			})
		});
	}

	setData(res){
		let arrears=0,months=0;
		let custInfo=res.custInfo;
		let custCode=custInfo.custCode;
		let custName=custInfo.custName;
		let tel=custInfo.tel;
		let address=custInfo.address;
		let orderNum=custInfo.orderNum;
		let bookName=custInfo.meterBooks.bookName;
		let balance=Number(custInfo.money).toFixed(2);
		let currMonth=this.state.currMonth;

		if(custInfo==null){
			Toast.show("抱歉，没有符合条件的记录！");
			return
		}else{
			this.setState({
				bookName:bookName,
				custCode:custCode,
				custName:custName,
				tel:tel,
				address: address,
				orderNum:orderNum,
				currMonth:currMonth,
				balance: balance,
				payfee:'',
			});
		}

		let costMaster=res.costMaster;
		if(costMaster==null){
			Alert.alert('提示','该用户不存在欠费！');
		}else{
			this.setState(
			{
				natureName:costMaster.natureName,
				arrears: costMaster.sumCharge,
				surplus:(balance-costMaster.sumCharge).toFixed(2),
				months:costMaster.currMonth,
				priorReading:costMaster.priorReading,
				currReading:costMaster.currReading,
				quantity:costMaster.quantity+costMaster.waterDamage,
				sumQuantity:costMaster.sumQuantity,
				waterCost:costMaster.waterCost,
				sewageCost:costMaster.sewageCost,
				healthCost:costMaster.healthCost,
				lateFee:costMaster.lateFee,
				sumFact:costMaster.sumFact,
				totalFact:costMaster.custAccount.totalFact,
			},()=>{
				if(this.state.arrears>0){
					if(this.state.balance>=this.state.arrears){
						this.setModalVisible(true);
					}
				}else{
					Toast.showShortBottom("该用户不存在欠费！");
				}
			})
		}
	}

	payTips(){
		let custCode = this.state.custCode;
		let custName = this.state.custName;
		let balance = parseFloat(this.state.balance).toFixed(2);
		let payfee=parseFloat(this.state.payfee).toFixed(2);
		let arrears=parseFloat(this.state.arrears).toFixed(2);
		let currMonth=this.state.currMonth;
		if (payfee==0 || typeof(payfee)=="undefined" || payfee == null || isNaN(payfee)) {
			Toast.showShortBottom('缴费金额不能为空或为零！');
			return;
		}

		const params = {
			custCode:custCode,
	  	};

		const data = {
			custName:custName,
			custCode:custCode,
			balance:balance,
			source:"app",
			payfee:payfee,
			arrears:arrears
	  	};

		this.fetchPayment(params)
		.then((res) => {
			if(res.length>0){
				Alert.alert('提示','本月已缴费，请勿重复缴费！');
				return;
			}else{
				Alert.alert('提示', '确定要交费'+this.state.payfee+'元吗？',
					[
						{
							text: '确定',
							onPress: ()=> this.pay(data)
						},
						{
							text: '取消',
							onPress: () => console.log('点击取消')
						}
					]
				)
			}
		}).catch((error)=>{
			Alert.alert(error);
		})
	}

	pay(data){
        let url=global.server.url+'/payment/pay';
		axiosInstance({
		  method: 'post',
		  url: url,
		  data: data
		})
        .then(res => {
        	if(res.success){

				Alert.alert(
					'提示', //提示标题
					'交费成功，是否打印票据？', //提示内容
					[
						{
							text: '确定',
							onPress: ()=> this.printBill()
						},
						{
							text: '取消',
							onPress: () => console.log('取消打印')
						}
					]
				)
			}else{
				Toast.showShortBottom('缴费失败！');
			}
        })
        .catch(err => {
        	Toast.showShortBottom("缴费时发生异常，请联系系统管理员:"+err);
        })
    }

	prepay(visible){
		let custCode = this.state.custCode;
		let custName = this.state.custName;
		let balance = parseFloat(this.state.balance).toFixed(2);
		let arrears=parseFloat(this.state.arrears).toFixed(2);
		let url=global.server.url+'/custPrepay/deduct';

		axiosInstance.post(url,
		{
			custCode:custCode,
			custName:custName,
			balance:balance,
			source:"app",
			payfee:"0.00",
			arrears:arrears,
			memo:'预存自动抵扣',
		}).then(res => {
        	if(res.success){
				Alert.alert(
					'提示', //提示标题
					'交费成功，是否打印票据？', //提示内容
					[
						{
							text: '确定',
							onPress: ()=> this.printBill()
						},
						{
							text: '取消',
							onPress: () => this.goBack(true)
						}
					] //按钮集合
				)
			}else{
				Toast.showShortBottom('保存失败！');
			}
        })
        .catch(err => {
        	Toast.showShortBottom("扣费时发生异常，请联系系统管理员:"+err);
        })
		this.setState({ modalVisible: visible });
	}

	changeMoney(payfee){
		//去掉以零开头的数字
		payfee=payfee.replace(/\b(0+)/gi,"");

		payfee = payfee.replace(/[^\d.]/g, "");
        //必须保证第一位为数字而不是.
        payfee = payfee.replace(/^\./g, "");
        //保证只有出现一个.而没有多个.
        payfee = payfee.replace(/\.{2,}/g, ".");
        //保证.只出现一次，而不能出现两次以上
        payfee = payfee.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");

		let arrears=Number(this.state.arrears);
		let balance=Number(this.state.balance);
		let surplus=Number(payfee)+balance-arrears;

		if(arrears>0){
			this.setState({
				surplus:surplus.toFixed(2),
				payfee:payfee
			});
		}
	}

	goBack = (visible) => {
		this.setState({ modalVisible: visible });
		const { params } = this.props.navigation.state;
		this.props.navigation.navigate(params.scene, {});
	}

	printBill(){
		const params = {
			custCode:this.state.custCode,
	  	};

		this.fetchPayment(params).then((res) => {
			let datas=res;
			if(datas.length==0){
				Alert.alert('提示','本月未发生缴费，无法打印！');
				return;
			}else{
				this.setState(
				{
					payfee:datas[0].payfees,
				},()=>{
					this.print();
				})
			}
		}).catch((error)=>{
			Alert.alert(error);
		})
	}

	print(){
		const Config = {
          wordNumber: 32
        }

        ESC.setConfig(Config)

        // 打印初始化
        ESC.init()
        ESC.alignCenter()
        ESC.fontBold()
        ESC.printAndNewLine()
        ESC.text('邬桥水厂')
        ESC.printAndNewLine()

        ESC.text('收款收据')
        ESC.printAndNewLine()
        ESC.printAndNewLine()

        ESC.init()
        ESC.text('用户名称：'+this.state.custName)
		ESC.printAndNewLine()

        ESC.text('用户户号：'+this.state.custCode)
		ESC.printAndNewLine()


        //ESC.text('用水性质：'+this.state.natureName)
		//ESC.printAndNewLine()

        ESC.text('详细地址：'+this.state.address)
		ESC.printAndNewLine()

        ESC.text(ESC.Util.leftCenterRight('上期表码：'+this.state.priorReading, '本期表码:'+this.state.currReading, '', 48))
        ESC.printAndNewLine()

		ESC.text(ESC.Util.leftCenterRight('总用水量：'+this.state.sumQuantity, '欠费月数：'+this.state.months, '', 48))
		ESC.printAndNewLine()

		ESC.text(ESC.Util.leftCenterRight('当月用量：'+this.state.quantity, '当月水费：'+this.state.waterCost, '', 48))
		ESC.printAndNewLine()

		ESC.text('应收金额:'+this.state.arrears)
		ESC.printAndNewLine()

		ESC.text('缴费金额:'+this.state.payfee)
		ESC.printAndNewLine()

		ESC.text('金额大写:'+DigitUtil.digitUppercase(this.state.payfee))
		ESC.printAndNewLine()

		ESC.text('用户余额：'+this.state.balance)
		ESC.printAndNewLine()

		ESC.text('本次结余:'+this.state.surplus)
		ESC.printAndNewLine()

        ESC.text('抢修电话:13233972306')

        ESC.printAndNewLine()
        ESC.alignRight()
        ESC.text('收费员：'+this.state.name)
        ESC.printAndNewLine()

		ESC.alignRight()
        ESC.text('收费日期：'+DateUtil.myformatter(new Date()))
        ESC.printAndNewLine()

        ESC.printAndNewLine()
        ESC.printAndNewLine()
        ESC.printAndNewLine()
        ESC.printAndNewLine()

        ESC.sound()
        ESC.init()

		console.log('===============缴费金额=================='+this.state.payfee);
		console.log('=============收据打印完成==================');
	}

	printArrearsBillCheck(){
		Alert.alert('提示', '确定要打印欠费通知单吗？',
			[
				{
					text: '确定',
					onPress: ()=> this.printArrearsBill()
				},
				{
					text: '取消',
					onPress: () => console.log('点击取消')
				}
			]
		)
	}

	// 打印欠费通知单小票
    printArrearsBill(){

		let arrears=this.state.arrears;
		if(arrears==0){
			Alert.alert('提示','该用户不存在欠费！');
			return;
		}

        const Config = {
          wordNumber: 32
        }

        ESC.setConfig(Config)

        // 打印初始化
        ESC.init()
        ESC.alignCenter()
        ESC.fontBold()
        ESC.printAndNewLine()
        ESC.text('邬桥水厂')
        ESC.printAndNewLine()

        ESC.text('欠费通知单')
        ESC.printAndNewLine()
        ESC.printAndNewLine()

        ESC.init()
        ESC.text('用户名称：'+this.state.custName)
		ESC.printAndNewLine()
		ESC.printAndNewLine()


        ESC.text('用户户号：'+this.state.custCode)
		ESC.printAndNewLine()
		ESC.printAndNewLine()

        //ESC.text('用水性质：'+this.state.natureName)
		//ESC.printAndNewLine()
		//ESC.printAndNewLine()

        ESC.text('详细地址：'+this.state.address)
		ESC.printAndNewLine()
        ESC.printAndNewLine()

        ESC.text(ESC.Util.leftCenterRight('上期表码：'+this.state.priorReading, '本期表码:'+this.state.currReading, '', 48))
        ESC.printAndNewLine()

		ESC.text(ESC.Util.leftCenterRight('总用水量：'+this.state.sumQuantity, '当月用量：'+this.state.quantity, '', 48))
        ESC.printAndNewLine()

		ESC.text(ESC.Util.leftCenterRight('欠费月数：'+this.state.months,'当月水费：'+this.state.waterCost, '', 48))
		ESC.printAndNewLine()

		ESC.text(ESC.Util.leftCenterRight('应收金额:'+arrears, '用户余额：'+this.state.balance, '', 48))
        ESC.printAndNewLine()

		ESC.text(ESC.Util.leftCenterRight('本次结余:'+this.state.surplus, '', '', 48))
        ESC.printAndNewLine()

        ESC.text('提示：请用户收到本通知单后，于本')
		ESC.printAndNewLine()
        ESC.text('月20日至28日前到我公司收费大厅缴')
		ESC.printAndNewLine()
        ESC.text('费,逾期将会产生滞纳金!(请记住要')
		ESC.printAndNewLine()
		ESC.text('缴费的用户编号或用户姓名，以方便')
		ESC.printAndNewLine()
		ESC.text('缴费)')

        ESC.printAndNewLine()
        ESC.alignRight()
        ESC.text('抄表人员：'+this.state.name)
        ESC.printAndNewLine()

		ESC.alignRight()
        ESC.text('抄表日期：'+DateUtil.myformatter(new Date()))
        ESC.printAndNewLine()

        ESC.printAndNewLine()
        ESC.printAndNewLine()
        ESC.printAndNewLine()
        ESC.printAndNewLine()

        ESC.sound()
        ESC.init()

		console.log('=============欠费通知单打印完成==================');
     }

	clear= () => {
		this.setState({
			payfee:''
		});
	}

	//扫码支付
  	payQrCode(){
		let custCode = this.state.custCode;
		let custName = this.state.custName;
		let balance = parseFloat(this.state.balance).toFixed(2);
		let payfee=parseFloat(this.state.payfee).toFixed(2);
		let arrears=parseFloat(this.state.arrears).toFixed(2);
		let currMonth=this.state.currMonth;

		if (payfee==0 || typeof(payfee)=="undefined" || payfee == null || isNaN(payfee)) {
			Toast.showShortBottom('缴费金额不能为空或为零！');
			return;
		}

		const params = {
			custCode:custCode,
	  	};

		this.fetchPayment(params).then((res) => {
			if(res.length>0){
				Alert.alert('提示','本月已缴费，请勿重复缴费！');
				return;
			}else{
				const data={
					custName:custName,
					custCode:custCode,
					balance:balance,
					source:"app",
					payfee:payfee,
					arrears:arrears
				};
				this.props.navigation.navigate('WxPayScene',data)
			}
		}).catch((error)=>{
			Alert.alert(error);
		})
	}

	/**
   	 * [android]
   	 * enable bluetooth on device
     */
  	enable () {
		BluetoothSerial.enable()
		.then((res) => this.setState({ isEnabled: true }))
		.catch((err) => Toast.showShortBottom(err.message))
  	}

	/**
	 * [android]
	 * disable bluetooth on device
	*/
  	disable () {
		BluetoothSerial.disable()
		.then((res) => this.setState({ isEnabled: false }))
		.catch((err) => Toast.showShortBottom(err.message))
  	}

	/**
	 * [android]
     * toggle bluetooth
     */
	toggleBluetooth (value) {
		if (value === true) {
		  this.enable()
		} else {
		  this.disable()
		}
	}

   /**
    * [android]
    * Discover unpaired devices, works only in android
    */
	discoverUnpaired () {
		if (this.state.discovering) {
		  return false
		} else {
		  this.setState({discovering:true})
		  BluetoothSerial.discoverUnpairedDevices()
		  .then((unpairedDevices) => {
			this.setState({ unpairedDevices, discovering: false })
		  })
		  .catch((err) => Toast.showShortBottom(err.message))
		}
	}

	render() {
		 styles=getStyles();
		 return (
			<View style={styles.container}>
				<View style={styles.items}>
					<Text style={styles.textStyle}>客户编号:</Text>
					<Text style={[styles.valueStyle,{width:width-105}]}>{this.state.custCode}</Text>
					<TouchableOpacity
							style={style.saveBtn}
							underlayColor='transparent'
							onPress={() => this.printArrearsBillCheck()}>
						<Text style={styles.saveText}>欠费打印</Text>
					</TouchableOpacity>
					<TouchableOpacity
							style={style.saveBtn}
							underlayColor='transparent'
							onPress={() => this.payTips()}>
						<Text style={styles.saveText}>现金交费</Text>
					</TouchableOpacity>
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>客户名称:</Text>
					<Text style={[styles.valueStyle,{width:width-105}]}>{this.state.custName}</Text>
					<TouchableOpacity
							style={style.saveBtn}
							underlayColor='transparent'
							onPress={() => this.printBill()}>
						<Text style={styles.saveText}>补打票据</Text>
					</TouchableOpacity>
					{
					<TouchableOpacity
							style={style.saveBtn}
							underlayColor='transparent'
							onPress={() => this.payQrCode()}>
						<Text style={styles.saveText}>扫码支付</Text>
					</TouchableOpacity>
					}
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>移动电话:</Text>
					<Text style={styles.valueStyle}>{this.state.tel}</Text>
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>详细地址:</Text>
					<Text style={styles.valueStyle}>{this.state.address}</Text>
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>缴费金额:</Text>
					<TextInput
						underlineColorAndroid="gray"
						placeholder="请输入缴费金额"
						autoFocus={true}
						keyboardType='numeric'
						clearButtonMode="while-editing"
						style={styles.inputStyle}
						value={this.state.payfee+''}
						onChangeText={(text) => this.changeMoney(text)}>
					</TextInput>
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>上期读数:</Text>
					<Text style={[styles.valueStyle,{width:width-110}]}>{this.state.priorReading}</Text>
					<Text style={styles.textStyle}>本期读数:</Text>
					<Text style={styles.valueStyle}>{this.state.currReading}</Text>
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>总用水量:</Text>
					<Text style={[styles.valueStyle,{width:width-110}]}>{this.state.sumQuantity}</Text>
					<Text style={styles.textStyle}>当月用量:</Text>
					<Text style={styles.valueStyle}>{this.state.quantity}</Text>
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>当月水费:</Text>
					<Text style={[styles.valueStyle,{width:width-110}]}>{this.state.waterCost}</Text>
					<Text style={styles.textStyle}>当月污水费:</Text>
					<Text style={styles.valueStyle}>{this.state.sewageCost}</Text>
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>当月卫生费:</Text>
					<Text style={[styles.valueStyle,{width:width-130}]}>{this.state.healthCost}</Text>
					<Text style={styles.textStyle}>当月滞纳金:</Text>
					<Text style={styles.valueStyle}>{this.state.lateFee}</Text>
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>欠费月数:</Text>
					<Text style={[styles.valueStyle,{width:width-110}]}>{this.state.months}</Text>
					<Text style={[styles.textStyle,{color:'red'}]}>应收金额:</Text>
					<Text style={styles.valueStyle}>{this.state.arrears}</Text>
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>用户余额:</Text>
					<Text style={[styles.valueStyle,{width:width-110}]}>{this.state.balance}</Text>
					<Text style={styles.textStyle}>本次结余:</Text>
					<Text style={styles.valueStyle}>{this.state.surplus}</Text>
				</View>
				<View style={{alignItems:'center',flex:1}}>
					<Modal
						animationType={this.state.animationType}
						transparent={this.state.transparent}
						visible={this.state.modalVisible}
						onRequestClose={() => {
							this.setModalVisible(false)
						}}
					>
						<View style={[styles.modalContainer,{backgroundColor: 'rgba(0, 0, 0, 0.5)'}]}>
							<View style={[styles.innerContainer,{backgroundColor: '#F0F8FF', padding: 20}]}>
								<View style={styles.row}>
									<View >
										<Text style={styles.tips}>该用户余额为{this.state.balance}元,累计欠费金额为：{this.state.arrears}元,确定要自动扣费吗？</Text>
									</View>
									<View style={styles.settingStyle}>
										<Text
											onPress={this.prepay.bind(this,false)}
											style={styles.btnStyle}>
											确定
										</Text>
										<Text
											onPress={this.goBack.bind(this,false)}
											style={styles.btnStyle}>
											关闭
										</Text>
									</View>
								</View>
							</View>
						</View>
					</Modal>
			</View>
		  </View>)
    }
}
const style = StyleSheet.create({
	saveBtn: {
		height:30,
		width:75,
		backgroundColor: 'green',
		margin: 5,
		justifyContent: 'center',
		borderRadius:5
	},
});

